package cn.autumnorange.app.money.consumer.controller;

import cn.autumnorange.app.common.dto.ResultDto;
import cn.autumnorange.app.money.api.MoneyService;
import cn.autumnorange.app.money.api.MoneyService2;
import cn.autumnorange.app.money.api.dto.MoneyDto;
import com.taobao.txc.client.aop.annotation.TxcTransaction;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

@Slf4j
@RestController
public class MoneyController implements MoneyService {
  @Autowired MoneyService moneyService;
  @Autowired MoneyService2 moneyService2;

  @TxcTransaction(timeout = 60000 * 5)
  @Override
  public ResponseEntity<ResultDto<MoneyDto>> add(
      @PathVariable(value = "version") Long version, @PathVariable(value = "money") Long money) {
    ResponseEntity<ResultDto<Long>> versionDto = moneyService.getVersion(1L);
    if (versionDto == null || versionDto.getStatusCodeValue() != HttpStatus.OK.value()) {
      throw new RuntimeException(versionDto.getBody().getMessage());
    }

    ResponseEntity<ResultDto<MoneyDto>> resultDto =
        moneyService.add(versionDto.getBody().getData(), money);

    if (resultDto == null || resultDto.getStatusCodeValue() != HttpStatus.OK.value()) {
      throw new RuntimeException(resultDto.getBody().getMessage());
    }
    versionDto = null;
    versionDto = moneyService2.getVersion(1L);
    if (versionDto == null || versionDto.getStatusCodeValue() != HttpStatus.OK.value()) {
      throw new RuntimeException(versionDto.getBody().getMessage());
    }
    resultDto = moneyService2.add2(versionDto.getBody().getData(), money);

    if (resultDto == null || resultDto.getStatusCodeValue() != HttpStatus.OK.value()) {
      throw new RuntimeException(resultDto.getBody().getMessage());
    }
    return resultDto;
  }

  @Override
  public ResultDto<MoneyDto> getmoney() {
    return moneyService.getmoney();
  }

  @Override
  public ResponseEntity<ResultDto<MoneyDto>> resetacc() {
    return moneyService.resetacc();
  }

  @Override
  public ResponseEntity<ResultDto<Long>> getVersion(Long id) {
    return null;
  }

  //  @Override
  //  public ResponseEntity<ResultDto<UserDetailDto>> loadUserByUsername(String name) {
  //    return null;
  //  }
  //
  //  @Override
  //  public ResponseEntity<ResultDto<UserDetailDto>> loginSuccess() {
  //
  //    Authentication authorization = SecurityContextHolder.getContext().getAuthentication();
  //    if (authorization != null) {
  //      Object obj = authorization.getPrincipal();
  //      if (obj instanceof UserDetails) {
  //        UserDetails userDetails = (UserDetails) authorization.getPrincipal();
  //        log.info(userDetails.toString());
  //      }
  //    }
  //
  //    return appUserService.loginSuccess();
  //  }
}
